﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using System.ComponentModel;
using System.Reflection;
using System.Text;
using System.Web;
using Masuit.Tools.AspNetCore.Extensions;
using YaseiAkira.AJ.Util;
using WebService.Models;
using WebService.Upload;
using static WebService.Upload.Uploader;


namespace WebService.Controllers.Platform
{
    /// <summary>
    /// 公共接口
    /// </summary>
    [ApiController]
    [Route("platform/[controller]/[action]")]
    public class CommonController : Controller
    {
        private IConfiguration _configuration;
        public CommonController(IConfiguration conf)
        {

            _configuration = conf;
        }

        /// <summary>
        /// 删除已上传的文件
        /// </summary>
        /// <param name="url">文件列表</param>
        /// <returns></returns>
        [HttpPost]
        public ObjectResult RemoveMedias([FromBody] string[] url)
        {
            var result = new ProcessResult();

            if (url == null || url.Length == 0)
            {
                Util.FriendlyError("参数错误");
            }

            var domain = Request.GetDomain();

            url = url.Where(p => !string.IsNullOrWhiteSpace(p))
                .Select(p => HttpUtility.UrlDecode(p.TrimStart().TrimEnd())).ToArray();

            Util.TryDeleteFiles(domain, url);

            return new ObjectResult(null);
        }

        /// <summary>
        /// 上传文件接口,前端 FormData 可以指定多个文件, 也可以自定义上传文件夹, 使用 category 参数,加入url的请求参数
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        [DisableFormValueModelBinding]
        public async Task<List<MediaItem>> Upload(string category = "默认图片")
        {
            category = HttpUtility.UrlDecode(category).TrimStart().TrimEnd();

            var result = await Request.UploadFilesAsync(category);

            if (!result.Success)
            {
                Util.FriendlyError(result.Message);
            }

            return result.Data as List<MediaItem>;
        }
    }
}
